import process from 'process'
import * as path from 'path'
import {getParser} from './test-parser'
import {TestResult} from '@flow-step/step-toolkit/src/testCase'
import * as step from '@flow-step/step-toolkit'

export async function execute() {
    let reportPath = process.env.REPORT_PATH as string
    const projectDir = process.env.PROJECT_DIR as string
    reportPath = path.join(projectDir, reportPath)
    const reporter = process.env.REPORTER as string

    // Java-JUnit / Node.js-Mocha / Golang-Test / Php-UnitTest ...
    const parser = getParser(reporter)
    const coverageFile = await parser.coverageFile(reportPath)
    const coverage = await parser.parse(coverageFile)
    step.debug(`coverage: ${JSON.stringify(coverage)}`)

    const htmlFilePath = parser.htmlFile(reportPath)
    const result = {
        reportLocalPath: htmlFilePath,
        coverage: coverage
    } as TestResult

    await step.testCase.outputResult(result)

    if (coverage.failed > 0 && process.env.FAIL_ON_ERROR == 'true') {
        throw new Error(`step failed because of failed test case(s)`)
    }
}

